<template>
  <AxiomDialog
    :model-value="visible"
    :title="title"
    width="700px"
    @close="handleClose"
    @cancel="handleClose"
    @confirm="handleConfirm"
    :confirm-loading="loading"
  >
    <AxiomForm ref="formRef" :model="formData" :rules="rules" label-width="140px">
      <AxiomFormItem label="客户端名称" prop="client_name">
        <AxiomInput v-model="formData.client_name" placeholder="请输入客户端名称"></AxiomInput>
      </AxiomFormItem>
      <AxiomFormItem label="客户端ID" prop="client_id">
        <AxiomInput v-model="formData.client_id" :disabled="isEdit" placeholder="请输入客户端ID"></AxiomInput>
      </AxiomFormItem>
      <AxiomFormItem v-if="!isEdit" label="客户端密钥" prop="client_secret">
        <AxiomInput v-model="formData.client_secret" placeholder="请输入客户端密钥"></AxiomInput>
      </AxiomFormItem>

      <AxiomFormItem label="授权类型" prop="grant_types">
        <AxiomCheckboxGroup v-model="formData.grant_types" :options="grantTypeOptions"></AxiomCheckboxGroup>
      </AxiomFormItem>

      <!-- [新增] 根据 grant_types 动态显示 -->
      <AxiomFormItem v-if="showRedirectUris" label="重定向URIs" prop="redirect_uris">
        <AxiomTagInput v-model="formData.redirect_uris" placeholder="输入URI后按回车确认"></AxiomTagInput>
      </AxiomFormItem>

      <!-- [新增] 根据 grant_types 动态显示 -->
      <AxiomFormItem v-if="showResponseTypes" label="响应类型" prop="response_types">
        <AxiomCheckboxGroup v-model="formData.response_types" :options="responseTypeOptions"></AxiomCheckboxGroup>
      </AxiomFormItem>

      <AxiomFormItem label="范围" prop="scope">
        <AxiomTree
          ref="scopeTreeRef"
          :data="permissionTree"
          :loading="permissionTreeLoading"
          show-checkbox
          node-key="permission_code"
          :props="{ label: 'permission_name', children: 'children' }"
          :default-expand-all="true"
          style="border: 1px solid var(--axiom-border-color-light); border-radius: 4px; padding: 8px;"
        />
      </AxiomFormItem>

      <AxiomFormItem label="Token认证方法" prop="token_endpoint_auth_method">
        <AxiomSelect
          v-model="formData.token_endpoint_auth_method"
          placeholder="请选择"
          :options="tokenEndpointAuthMethodOptions"
          block
        ></AxiomSelect>
      </AxiomFormItem>
    </AxiomForm>
  </AxiomDialog>
</template>

<script setup>
import { ref, reactive, computed, watch, inject, nextTick } from 'vue';
import {
  AxiomDialog,
  AxiomFormItem,
  AxiomInput,
  AxiomSelect,
  AxiomCheckboxGroup,
  AxiomTagInput,
  AxiomForm,
  AxiomTree,
} from 'axiom-view';
import { createClient, updateClient, retrieveClientDetails } from '@/api/system/client';
import { getPermissionTree } from '@/api/system/permission';

const props = defineProps({
  visible: Boolean,
  mode: {
    type: String,
    default: 'add', // 'add' or 'edit'
  },
  initialData: {
    type: Object,
    default: () => ({}),
  },
});

const emit = defineEmits(['close', 'success']);
const { notification } = inject('axiom-utils');
const formRef = ref(null);
const scopeTreeRef = ref(null);
const permissionTree = ref([]);
const permissionTreeLoading = ref(false);

const stringToArray = (value, separator = ',') => {
  if (typeof value === 'string' && value.length > 0) {
    return value.split(separator);
  }
  return [];
};

const defaultFormData = {
  client_id: '',
  client_secret: '',
  client_name: '',
  redirect_uris: [],
  grant_types: ['authorization_code', 'refresh_token'],
  response_types: ['code'],
  scope: [],
  token_endpoint_auth_method: 'client_secret_post',
};

const loading = ref(false);
const formData = reactive({ ...defaultFormData });

const showRedirectUris = computed(() => formData.grant_types.includes('authorization_code'));
const showResponseTypes = computed(() => formData.grant_types.includes('authorization_code'));

const grantTypeOptions = ref([
  { label: 'authorization_code', value: 'authorization_code' },
  { label: 'password', value: 'password' },
  { label: 'client_credentials', value: 'client_credentials' },
  { label: 'refresh_token', value: 'refresh_token' },
]);

const responseTypeOptions = ref([
  { label: 'code', value: 'code' },
  { label: 'token', value: 'token' },
]);

const tokenEndpointAuthMethodOptions = ref([
  { label: 'client_secret_post', value: 'client_secret_post' },
  { label: 'client_secret_basic', value: 'client_secret_basic' },
  { label: 'none', value: 'none' },
]);

const rules = reactive({
  client_name: [{ required: true, message: '请输入客户端名称', trigger: 'blur' }],
  client_id: [{ required: true, message: '请输入客户端ID', trigger: 'blur' }],
  client_secret: [{ required: true, message: '请输入客户端密钥', trigger: 'blur' }],
  redirect_uris: [{
    required: true,
    type: 'array',
    min: 1,
    message: '至少需要一个重定向URI',
    validator: (rule, value, callback) => {
      if (showRedirectUris.value && (!value || value.length === 0 || value.every(v => !v.trim()))) {
        callback(new Error('至少需要一个重定向URI'));
      } else {
        callback();
      }
    },
    trigger: 'change'
  }],
  grant_types: [{ required: true, type: 'array', min: 1, message: '至少选择一种授权类型', trigger: 'change' }],
  response_types: [{
    required: true,
    type: 'array',
    min: 1,
    message: '至少选择一种响应类型',
    trigger: 'change'
  }],
  scope: [], // [修改] 范围不再是必填项
  token_endpoint_auth_method: [{ required: true, message: '请选择Token认证方法', trigger: 'change' }],
});

const isEdit = computed(() => props.mode === 'edit');
const title = computed(() => (isEdit.value ? '编辑客户端' : '新增客户端'));

watch(() => formData.grant_types, (newGrantTypes) => {
  const hasAuthCode = newGrantTypes.includes('authorization_code');
  rules.redirect_uris[0].required = hasAuthCode;
  rules.response_types[0].required = hasAuthCode;

  if (hasAuthCode) {
    if (!formData.response_types.includes('code')) {
      formData.response_types = ['code'];
    }
  } else {
    formData.redirect_uris = [];
    formData.response_types = [];
  }

  if (formRef.value) {
    formRef.value.clearValidate(['redirect_uris', 'response_types']);
  }
}, { deep: true });

const fetchPermissions = async () => {
  permissionTreeLoading.value = true;
  try {
    const res = await getPermissionTree();
    permissionTree.value = (res.success && res.data) ? res.data : [];
  } catch (error) {
    console.error("加载权限树失败:", error);
    permissionTree.value = [];
  } finally {
    permissionTreeLoading.value = false;
  }
};

watch(() => props.visible, async (val) => {
  if (val) {
    await fetchPermissions(); // 首先加载权限树

    if (props.mode === 'edit' && props.initialData && props.initialData.id) {
      try {
        const res = await retrieveClientDetails(props.initialData.id);
        if (res.success && res.data) {
          Object.assign(formData, {
            ...res.data,
            redirect_uris: stringToArray(res.data.redirect_uris, ','),
            grant_types: stringToArray(res.data.grant_types, ','),
            response_types: stringToArray(res.data.response_types, ','),
            scope: stringToArray(res.data.scope, ' '), // [修改] 按空格分割 scope
          });

          await nextTick();
          if (scopeTreeRef.value) {
            scopeTreeRef.value.setCheckedKeys(formData.scope);
          }
        }
      } catch (error) {
        console.error("加载客户端详情失败:", error);
        Object.assign(formData, { ...props.initialData });
      }
    } else {
      Object.assign(formData, JSON.parse(JSON.stringify(defaultFormData)));
      await nextTick();
      if (scopeTreeRef.value) {
        scopeTreeRef.value.setCheckedKeys([]);
      }
    }
  } else {
    handleClose();
  }
});

const handleClose = () => {
  Object.assign(formData, JSON.parse(JSON.stringify(defaultFormData)));
  permissionTree.value = [];
  if (formRef.value) {
    formRef.value.resetFields();
  }
  emit('close');
};

const handleConfirm = async () => {
  try {
    if (!formRef.value) return;
    await formRef.value.validate();

    loading.value = true;

    const checkedKeys = scopeTreeRef.value ? scopeTreeRef.value.getCheckedKeys() : [];
    const halfCheckedKeys = scopeTreeRef.value ? scopeTreeRef.value.getHalfCheckedKeys() : [];

    const payload = {
      ...formData,
      redirect_uris: showRedirectUris.value ? formData.redirect_uris.join(',') : '',
      grant_types: formData.grant_types.join(','),
      response_types: showResponseTypes.value ? formData.response_types.join(',') : '',
      scope: [...checkedKeys, ...halfCheckedKeys].join(' '), // [修改] 用空格拼接 scope
    };

    if (props.mode === 'add') {
      await createClient(payload);
      notification.success({ title: '成功', message: '新增成功' });
    } else {
      await updateClient(formData.id, payload);
      notification.success({ title: '成功', message: '更新成功' });
    }

    emit('success');
  } catch (error) {
    console.error('客户端表单提交失败:', error);
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped>
</style>